/*
 ----------------------------------------------------------------------------------
                           "THE BEER-WARE COPYRIGHT LICENSE"
                                     (Revision 43)
                                      -----------
    Rymek [rymek@rymek.org] wrote this file. As long as You retain this notice and
    this file has been sent directly to You by the author, You can do whatever You
    want with this stuff as long as You don't sell or rent it. If we meet some day,
    and You think this stuff is worth it, You can buy me a beer in return :-)
                                                                 __________
                                                                 Paweł Rymaszewski
  ----------------------------------------------------------------------------------
 */

package processing.logic.util;

import processing.objects.Server;

import java.sql.*;
import java.util.Observable;

/**
 * Abstract class containing methods for manipulating database connections.
 *
 * @author rymek
 *         User: rymek
 *         Date: 30.06.11
 *         Time: 10:21
 */
public abstract class Connector extends Observable {

    protected final Server server;                 // server details
    protected Connection connection;               // connection object
    protected PreparedStatement preparedStatement; // PreparedStatement object bound to this Connection
    protected ResultSet resultSet;                 // ResultSet object bound to this Connection

    /**
     * Constructor.
     * Creates reference to Server object.
     *
     * @param server Server Information
     */
    protected Connector(Server server) {
        this.server = server;
    }

    /**
     * Creates database connection.
     *
     * @throws SQLException thrown when connection cannot be established
     */
    protected void createConnection() throws SQLException {

        if (this.connection == null || this.connection.isClosed()) {
            this.connection = DriverManager.getConnection(
                    this.server.getConnectionUrl(),
                    this.server.getUserName(), this.server.getUserPass());
        }
    }

    /**
     * Performs cleanup of any open database related objects
     *
     * @throws SQLException thrown when error occurs
     */
    public void cleanup() throws SQLException {
        if (this.resultSet != null) this.resultSet.close();
        if (this.preparedStatement != null) this.preparedStatement.close();
        if (this.connection != null && !this.connection.isClosed()) this.connection.close();
    }

}
